package com.atguigu.petstore.sys.controller;

import com.atguigu.petstore.common.result.Result;
import com.atguigu.petstore.sys.biz.SysCaptchaService;
import com.atguigu.petstore.sys.biz.SysLoginService;
import com.atguigu.petstore.sys.vo.SysLoginResp;
import com.atguigu.petstore.sys.vo.SysLoginVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.Buffer;

/**
 * @author lfy
 * @Description 登录和验证码  biz： business
 * @create 2023-09-22 8:52
 * 1、以后所有Post请求要提交数据都用json提交，文件上传除外
 */
@Tag(name = "登录、验证码")
@RequestMapping("/api/sys")
@RestController
public class SysLoginController {

    @Autowired
    SysLoginService sysLoginService;

    @Autowired
    SysCaptchaService sysCaptchaService;


    @GetMapping("/captcha")
    public void  getCaptcha(HttpServletResponse response,
                            @RequestParam("deviceId") String deviceId) throws IOException {


        BufferedImage bufferedImage = sysCaptchaService.generateCaptcha(deviceId);


        //告诉浏览器这个是图片
        response.setContentType("image/jpeg");
        //写给浏览器
        ImageIO.write(bufferedImage,"jpeg",response.getOutputStream());

    }


    @Operation(summary = "系统用户登录")
    @PostMapping("/user/login")
    public Result login(@RequestBody SysLoginVo loginVo){


        //登录业务，返回令牌
        SysLoginResp resp = sysLoginService.login(loginVo);



        //将令牌交给前端，前端自行存储好，以后请求前端都带上
        return Result.ok(resp);
    }

    @Operation(summary = "检查用户令牌是否合法")
    @GetMapping("/user/token/check")
    public Result checkToken(@RequestHeader("token") String token){
        sysLoginService.checkToken(token);
        return Result.ok();
    }



    @Operation(summary = "用户退出")
    @PostMapping("/user/logout")
    public Result logout(@RequestHeader("token") String token){

        //把令牌删除，前端就算以后再带着令牌，这个是非法令牌。前端导航守卫会检查
        sysLoginService.logout(token);

        return Result.ok();
    }
}
